﻿using FastIOC.Annotation;
using FastUtil.Base;
using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FastExecutor.Base.Util
{
    [Component]
    public class TemplateUtil
    {
        private VelocityEngine vltEngine { set; get; }
        public string CodeTempPath { set; get; }
        public TemplateUtil()
        {
            CodeTempPath = System.Configuration.ConfigurationManager.AppSettings["CodeTempPath"];
            DirectoryInfo CodePath = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/" + CodeTempPath));
            if (!CodePath.Exists)
            {
                CodePath.Create();
            }
            vltEngine = new VelocityEngine();
            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.HttpContext.Current.Server.MapPath("~/Template/"));
            vltEngine.Init();
        }

        public string GeneratemeplateFile(string FileID, string TableName, string TemplateFileName, string CodeFileName, Dictionary<string, object> RenderDataDic)
        {
            DirectoryInfo CodePath = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/" + CodeTempPath + "/" + FileID));
            if (!CodePath.Exists)
            {
                CodePath.Create();
            }
            CodePath = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/" + CodeTempPath + "/" + FileID + "/" + TableName));
            if (!CodePath.Exists)
            {
                CodePath.Create();
            }
            VelocityContext vltContext = new VelocityContext();
            foreach (var item in RenderDataDic)
            {
                vltContext.Put(item.Key, item.Value);
            }
            Template vltTemplate = vltEngine.GetTemplate(TemplateFileName);
            System.IO.StringWriter vltWriter = new System.IO.StringWriter();
            vltTemplate.Merge(vltContext, vltWriter);
            string CodeContent = vltWriter.GetStringBuilder().ToString();
            string CodeFilePath = System.Web.HttpContext.Current.Server.MapPath("~/" + CodeTempPath + "/" + FileID + "/" + TableName + "/" + CodeFileName);
            //保存生成后的代码内容到文件
            FileUtil.SaveString2File(CodeFilePath, CodeContent);
            return CodeFilePath;
        }
    }
}
